<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="900px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
      class="device-driver-form"
    >
      <!-- 基础信息 -->
      <div class="form-section">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="驱动名称" prop="driverName">
              <el-input v-model="formData.driverName" placeholder="请输入驱动名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="formData.brand" placeholder="请输入品牌" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="formData.model" placeholder="请输入型号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备地址" prop="deviceAddress">
              <el-input v-model="formData.deviceAddress" placeholder="请输入设备地址" clearable>
                <template #append>
                  <el-button @click="mapVisible = true" type="primary" plain>选址</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="4区16位写功能码" prop="codeWrite">
              <el-input
                v-model="formData.codeWrite"
                placeholder="请输入4区16位写功能码"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯口" prop="codeWrite">
              <el-select
                v-model="formData.commPortId"
                placeholder="请选择通讯口"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="data in commPortList"
                  :key="data.id"
                  :label="data.portName"
                  :value="data.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 时间配置 -->
      <div class="form-section">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="最小采集时间(ms)" prop="minCollectTime">
              <el-input-number
                v-model="formData.minCollectTime"
                :min="0"
                :step="100"
                placeholder="请输入最小采集时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯等待时间(ms)" prop="commWaitTime">
              <el-input-number
                v-model="formData.commWaitTime"
                :min="0"
                :step="100"
                placeholder="请输入通讯等待时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="通讯间隔时间(ms)" prop="commIntervalTime">
              <el-input-number
                v-model="formData.commIntervalTime"
                :min="0"
                :step="100"
                placeholder="请输入通讯间隔时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 数据类型配置 -->
      <div class="form-section">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="16位整型" prop="int16AddressRange">
              <el-select
                v-model="formData.int16AddressRange"
                placeholder="请选择16位整型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_DEVICE_INT16)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="32/64位整型" prop="int3264AddressRan">
              <el-select
                v-model="formData.int3264AddressRan"
                placeholder="请选择32/64位整型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_DEVICE_INT3264)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="32/64位浮点型" prop="float3264AddressRange">
              <el-select
                v-model="formData.float3264AddressRange"
                placeholder="请选择32/64位浮点型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_DEVICE_FLOAT3264)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字符串字节序" prop="stringByteOrder">
              <el-select
                v-model="formData.stringByteOrder"
                placeholder="请选择字符串字节序"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_DEVICE_STRINGBYTE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="字符串编码" prop="stringEncoding">
              <el-select
                v-model="formData.stringEncoding"
                placeholder="请选择字符串编码"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_DEVICE_ENCODE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分块采集方式" prop="blockCollectMode">
              <el-select
                v-model="formData.blockCollectMode"
                placeholder="请选择分块采集方式"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.MQTT_DEVICE_BLOCK)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 描述信息 -->
      <div class="form-section">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="3"
                placeholder="请输入描述信息"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" size="default">取 消</el-button>
        <el-button @click="submitForm" type="primary" :disabled="formLoading" size="default">
          <el-icon v-if="formLoading" class="is-loading"><Loading /></el-icon>
          确 定
        </el-button>
      </div>
    </template>

    <!-- 腾讯地图选择器 -->
    <Dialog title="选择设备地址" v-model="mapVisible" width="800px">
      <TencentMapSelector @location-selected="onMapLocationSelected" />
    </Dialog>
  </Dialog>
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { DeviceDriverApi, DeviceDriverVO } from '@/api/mqtt/devicedriver'
import { CommPortApi } from '@/api/mqtt/commport'
import TencentMapSelector from '@/views/mqtt/device/TencentMapSelector.vue'

/** 设备驱动 表单 */
defineOptions({ name: 'DeviceDriverForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const commPortList = ref([]) // 通讯口列表
const deviceId = ref()
const mapVisible = ref(false) // 地图选择器显示状态
const formData = ref({
  id: undefined,
  deviceId: undefined,
  commPortId: undefined,
  driverName: undefined,
  brand: undefined,
  model: undefined,
  deviceAddress: undefined,
  minCollectTime: undefined,
  commWaitTime: undefined,
  int16AddressRange: undefined,
  int3264AddressRan: undefined,
  float3264AddressRange: undefined,
  stringByteOrder: undefined,
  stringEncoding: undefined,
  blockCollectMode: undefined,
  codeWrite: undefined,
  commIntervalTime: undefined,
  description: undefined
})

const formRules = reactive({
  commPortId: [{ required: true, message: '通讯口不能为空', trigger: 'change' }],
  driverName: [{ required: true, message: '驱动名称不能为空', trigger: 'blur' }],
  brand: [{ required: true, message: '品牌不能为空', trigger: 'blur' }],
  model: [{ required: true, message: '型号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 获取通讯口列表 */
const getCommPortList = async () => {
  try {
    commPortList.value = await CommPortApi.simpleList()
    console.log('commPortList', commPortList.value)
  } catch (error) {
    console.error('获取通讯口列表失败:', error)
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number, device?: any) => {
  console.log('open:', device)
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  deviceId.value = device.id
  resetForm()
  // 获取通讯口列表
  await getCommPortList()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceDriverApi.getDeviceDriver(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    formData.value.deviceId = deviceId.value
    const data = formData.value as unknown as DeviceDriverVO
    if (formType.value === 'create') {
      await DeviceDriverApi.createDeviceDriver(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceDriverApi.updateDeviceDriver(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 地图选择处理 */
const onMapLocationSelected = (result: any) => {
  // 只获取地址名称，不保存经纬度
  if (result?.address) {
    formData.value.deviceAddress = result.address
  }
  mapVisible.value = false
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceId: undefined,
    commPortId: undefined,
    driverName: undefined,
    brand: undefined,
    model: undefined,
    deviceAddress: undefined,
    minCollectTime: undefined,
    commWaitTime: undefined,
    int16AddressRange: undefined,
    int3264AddressRan: undefined,
    float3264AddressRange: undefined,
    stringByteOrder: undefined,
    stringEncoding: undefined,
    blockCollectMode: undefined,
    codeWrite: undefined,
    commIntervalTime: undefined,
    description: undefined
  }
  formRef.value?.resetFields()
}
</script>